<template>
    <el-dialog
            :close-on-click-modal="false"
            :title="!dataForm.id ? '新增' : '修改'"
            :visible.sync="visible">
        <el-form ref="dataForm" :model="dataForm" :rules="dataRule" label-width="100px"
                 @keyup.enter.native="dataFormSubmit()">
            <el-row>
                <el-col :span="8">
                    <el-form-item label="用户名" prop="userName">
                        <el-input v-model="dataForm.userName" placeholder="登录帐号"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item :class="{ 'is-required': !dataForm.id }" label="密码" prop="password">
                        <el-input v-model="dataForm.password" placeholder="密码" show-password></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item :class="{ 'is-required': !dataForm.id }" label="确认密码" prop="comfirmPassword">
                        <el-input v-model="dataForm.comfirmPassword" placeholder="确认密码" show-password></el-input>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="8">
                    <el-form-item label="姓名" prop="name">
                        <el-input v-model="dataForm.name" placeholder="姓名"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="邮箱">
                        <el-input v-model="dataForm.email" placeholder="邮箱"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="手机号">
                        <el-input v-model="dataForm.mobile" placeholder="手机号"></el-input>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="16">
                    <el-form-item label="工作单位" prop="company">
                        <el-input v-model="dataForm.company" placeholder="工作单位"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="职务" prop="operType">
                        <!--    <el-input v-model="dataForm.operType" placeholder="职务"></el-input>-->
                        <el-select v-model="dataForm.operType" placeholder="请选择职务类型">
                            <el-option v-for="(year,idx) of typeList" :key="idx" :label="year.label"
                                       :value="year.value"></el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="24">
                    <el-form-item label="地址" prop="address">
                        <el-input v-model="dataForm.address" placeholder="地址"></el-input>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-form-item label="系统角色" prop="roleIdList" size="mini">
                <el-checkbox-group v-model="dataForm.roleIdList">
                    <el-checkbox v-for="role in roleList" :key="role.roleId" :label="role.roleId">{{
							role.roleName
                        }}
                    </el-checkbox>
                </el-checkbox-group>
            </el-form-item>
            <el-form-item label="状态" prop="status" size="mini">
                <el-radio-group v-model="dataForm.status">
                    <el-radio :label="0">禁用</el-radio>
                    <el-radio :label="1">正常</el-radio>
                </el-radio-group>
            </el-form-item>
            <el-form-item label="授权区域" size="mini">
                <el-tree
                        ref="areaListTree"
                        :data="areaList"
                        :props="areaListTreeProps"
                        node-key="areaId"
                        show-checkbox>
                </el-tree>
            </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="dataFormSubmit()">确定</el-button>
    </span>
    </el-dialog>
</template>

<script>
import {isEmail, isMobile} from '@/utils/validate'
import {Debounce} from '@/utils/debounce'
import {encrypt} from '@/utils/crypto'
import {treeDataTranslate} from '@/utils'

export default {
    data() {
        var validatePassword = (rule, value, callback) => {
            console.info("validatePassword")
            if (!this.dataForm.id && !/\S/.test(value)) {
                callback(new Error('密码不能为空'))
            } else {
                console.info("开始密码设置------------")
                let minLength = 8;
                let hasUpperCase = /[A-Z]/.test(value);
                let hasLowerCase = /[a-z]/.test(value);
                let hasNumbers = /\d/.test(value);
                let hasSpecialChars = /[\W_]/.test(value);
                let errormsg = '';

                //console.info("显示ERROFMSG")
                // 检查密码长度
                if (value.length < minLength) {
                    errormsg = errormsg + '最少8位;';
                }
                //console.info("校验长度"+errormsg)
                // 检查是否包含大写字母
                if (!hasUpperCase) {
                    errormsg = errormsg + '含大写字母;';
                }
                // 检查是否包含小写字母
                if (!hasLowerCase) {
                    errormsg = errormsg + '含小写字母;';
                }
                // 检查是否包含数字
                if (!hasNumbers) {
                    errormsg = errormsg + '含数字;';
                }
                // 检查是否包含特殊字符
                if (!hasSpecialChars) {
                    errormsg = errormsg + '含特殊字符;';
                }

                //console.info(errormsg)
                if (errormsg != '') {
                    callback(new Error(errormsg))
                } else {
                    callback()
                }
            }
        }

        var validateComfirmPassword = (rule, value, callback) => {

            //console.info("开始密码设置------------")
            let minLength = 8;
            let hasUpperCase = /[A-Z]/.test(value);
            let hasLowerCase = /[a-z]/.test(value);
            let hasNumbers = /\d/.test(value);
            let hasSpecialChars = /[\W_]/.test(value);
            let errormsg = '';

            //console.info("显示ERROFMSG")
            // 检查密码长度
            if (value.length < minLength) {
                errormsg = errormsg + '密码最少8位;';
            }
            //console.info("校验长度"+errormsg)
            // 检查是否包含大写字母
            if (!hasUpperCase) {
                errormsg = errormsg + '含大写字母;';
            }
            // 检查是否包含小写字母
            if (!hasLowerCase) {
                errormsg = errormsg + '含小写字母;';
            }
            // 检查是否包含数字
            if (!hasNumbers) {
                errormsg = errormsg + '含数字;';
            }
            // 检查是否包含特殊字符
            if (!hasSpecialChars) {
                errormsg = errormsg + '包含特殊字符;';
            }
            if (!this.dataForm.id && !/\S/.test(value)) {
                this.dataForm.password = ''
                callback(new Error('确认密码不能为空'))
            } else if (this.dataForm.password !== value) {
                callback(new Error('确认密码与密码输入不一致'))
            } else if (errormsg != '') {
                callback(new Error(errormsg))
            } else {
                callback()
            }
        }
        return {
            visible: false,
            roleList: [],
            areaList: [],
            areaListTreeProps: {
                label: 'areaName',
                children: 'children'
            },
            typeList: [
                {label: '管理员', value: '管理员'},
                {label: '审批员', value: '审批员'},
                {label: '专家', value: '专家'},
                {label: '填报员', value: '填报员'}
            ],
            dataForm: {
                id: 0,
                userName: '',
                password: '',
                comfirmPassword: '',
                email: '',
                mobile: '',
                roleIdList: [],
                areaIdList: [],
                status: 1,
                name: '',
                operType: '',
                address: '',
                company: '',
                sex: ''
            },
            dataRule: {
                userName: [
                    {required: true, message: '系统登录名不能为空', trigger: 'blur'},
                    {pattern: /\s\S+|S+\s|\S/, message: '请输入正确的系统登录名', trigger: 'blur'}
                ],
                password: [
                    {validator: validatePassword, required: true, trigger: 'blur'}
                ],
                comfirmPassword: [
                    {validator: validateComfirmPassword, required: true, trigger: 'blur'}
                ],
                name: [
                    {required: true, message: '姓名不能为空', trigger: 'blur'},
                    {trigger: 'blur', message: '请输入正确的姓名'}
                ],
                operType: [
                    {required: true, message: '职务类型', trigger: 'blur'},
                    {trigger: 'blur', message: '请选择正确的职务'}
                ]

            },
            tempKey: -666666 // 临时key, 用于解决tree半选中状态项不能传给后台接口问题. # 待优化
        }
    },
    methods: {
        init(id) {
            this.dataForm = {
                id: 0,
                userName: '',
                password: '',
                comfirmPassword: '',
                email: '',
                mobile: '',
                roleIdList: [],
                areaIdList: [],
                status: 1,
                name: '',
                operType: '',
                address: '',
                company: '',
                sex: ''
            }

            this.dataForm.id = id || 0

            this.$http({
                url: this.$http.adornUrl('/sys/role/listbyuser'),
                method: 'get',
                params: this.$http.adornParams()
            }).then(({data}) => {
                this.roleList = data
            }).then(() => {
                this.visible = true
                this.$nextTick(() => {
                    this.$refs.dataForm.resetFields()
                })
            }).then(() => {
                this.$http({
                    url: this.$http.adornUrl(`/sys/area/nav`),
                    method: 'get',
                    params: this.$http.adornParams()
                }).then(({data}) => {
                    // console.info('areadata')
                    // console.info(data)
                    this.areaList = treeDataTranslate(data, 'areaId', 'parentId')
                })
            }).then(() => {
                this.visible = true
                this.$nextTick(() => {
                    this.$refs['dataForm'].resetFields()
                    this.$refs.areaListTree.setCheckedKeys([])
                })
            }).then(() => {
                if (this.dataForm.id) {
                    this.$http({
                        url: this.$http.adornUrl(`/sys/user/info/${this.dataForm.id}`),
                        method: 'get',
                        params: this.$http.adornParams()
                    }).then(({data}) => {
                        this.dataForm.userName = data.username
                        this.dataForm.email = data.email
                        this.dataForm.mobile = data.mobile
                        this.dataForm.roleIdList = data.roleIdList
                        this.dataForm.status = data.status
                        this.dataForm.name = data.name
                        this.dataForm.company = data.company
                        this.dataForm.address = data.address
                        this.dataForm.sex = data.sex
                        this.dataForm.operType = data.operType
                        this.dataForm.areaIdList = data.areaIdList
                        var idx = data.areaIdList.indexOf(this.tempKey)
                        if (idx !== -1) {
                            data.areaIdList.splice(idx, data.areaIdList.length - idx)
                        }
                        // console.log(data.areaIdList)
                        this.$refs.areaListTree.setCheckedKeys(data.areaIdList)
                    })
                }
            })
        },
        // 表单提交
        dataFormSubmit: Debounce(function () {
            this.$refs['dataForm'].validate((valid) => {
                if (valid) {
                    this.$http({
                        url: this.$http.adornUrl(`/sys/user`),
                        method: this.dataForm.id ? 'put' : 'post',
                        data: this.$http.adornData({
                            'userId': this.dataForm.id || undefined,
                            'username': this.dataForm.userName,
                            'password': encrypt(this.dataForm.password),
                            'email': this.dataForm.email,
                            'mobile': this.dataForm.mobile,
                            'status': this.dataForm.status,
                            'address': this.dataForm.address,
                            'name': this.dataForm.name,
                            'operType': this.dataForm.operType,
                            'company': this.dataForm.company,
                            'sex': this.dataForm.sex,
                            'roleIdList': this.dataForm.roleIdList,
                            'areaIdList': [].concat(this.$refs.areaListTree.getCheckedKeys(), [this.tempKey], this.$refs.areaListTree.getHalfCheckedKeys())
                        })
                    }).then(({data}) => {
                        this.dataForm.email = ''
                        this.dataForm.mobile = ''
                        this.dataForm.id = ''
                        this.dataForm.userName = ''

                        this.$message({
                            message: '操作成功',
                            type: 'success',
                            duration: 1500,
                            onClose: () => {


                                this.visible = false
                                this.$emit('refreshDataList')
                            }
                        })
                    })
                }
            })
        })
    }
}
</script>
